import {
  onMounted,
  ref,
  watch,
  Ref,
  reactive,
  getCurrentInstance
} from "@vue/composition-api";
import { Message, MessageBox } from "element-ui";
import {
  addUserToGroup,
  createUserGroup,
  deleteUserGroup,
  getNoUsersDataByGroup,
  getUserGroupData,
  getUsersDataByGroup,
  GroupUserItem,
  removeUserFromGroup,
  updateUserGroup,
  UserGroupItem
} from "@/api/system-manage/user-group";
import { clone } from "@/utils";
import { OperationType, recordOperateLogFunc } from "@/api/log";

const recordOperateLog: Function = recordOperateLogFunc(
  "系统管理",
  "用户组管理"
);

// 重置用户列表函数
let resetUserList: Function;

// 刷新用户组列表函数
let refreshGroupList: Function;

export function useUserGroupList() {
  const groupList: Ref<UserGroupItem[]> = ref([]);
  const groupType = ref(1);

  const hasLoading = ref(true);

  refreshGroupList = async () => {
    hasLoading.value = true;
    groupList.value = await getUserGroupData(groupType.value);
    hasLoading.value = false;
    recordOperateLog(OperationType.Select);
  };

  onMounted(refreshGroupList);
  watch([groupType], () => {
    refreshGroupList();
    resetUserList();
  });

  function handleDeleteRow(row: UserGroupItem) {
    MessageBox.confirm(`真的要删除${row.emgname}这个用户组么？`, "提示", {
      type: "warning"
    }).then(async () => {
      const detail = await deleteUserGroup(row.emgid);
      if (detail) {
        refreshGroupList();
        Message.success(detail);
        recordOperateLog(OperationType.Delete);
      }
    });
  }

  return {
    groupList,
    groupType,
    hasLoading,

    handleDeleteRow
  };
}

export function useAllotUsers() {
  // 当前选择的用户组
  const selectedGroupId = ref("");

  // 视图显示的用户列表
  const userList: Ref<GroupUserItem[]> = ref([]);
  const noUserList: Ref<GroupUserItem[]> = ref([]);

  // 用户列表关键词
  const userKeyword = ref("");
  const noUserKeyword = ref("");

  // 选中的用户
  const userSelected: Ref<GroupUserItem> = ref(undefined);
  const noUserSelected: Ref<GroupUserItem> = ref(undefined);

  const userListLoading = ref(false);
  const noUserListLoading = ref(false);

  // 请求获得的用户列表
  const userData: Ref<GroupUserItem[]> = ref([]);
  const noUserData: Ref<GroupUserItem[]> = ref([]);

  watch(selectedGroupId, refreshUserList);

  // 关键词查出用户
  watch(userKeyword, async () => {
    if (userKeyword.value.length !== 0) {
      userList.value = userData.value.filter(
        t =>
          t.username.includes(userKeyword.value) ||
          t.cnname.includes(userKeyword.value)
      );
    }
  });

  watch(noUserKeyword, async () => {
    if (noUserKeyword.value.length !== 0) {
      noUserList.value = noUserData.value.filter(
        t =>
          t.username.includes(noUserKeyword.value) ||
          t.cnname.includes(noUserKeyword.value)
      );
    }
  });

  // 用户列表刷新
  async function refreshUserList() {
    userListLoading.value = true;
    noUserListLoading.value = true;

    userKeyword.value = "";
    noUserKeyword.value = "";

    getUsersDataByGroup(selectedGroupId.value).then(detail => {
      userData.value = detail;
      userList.value = detail;
      userListLoading.value = false;
    });

    const detail = await getNoUsersDataByGroup(selectedGroupId.value);
    noUserData.value = detail;
    noUserList.value = detail;
    noUserListLoading.value = false;
  }

  // 用户组改变事件
  function handleSelectGroup(row: UserGroupItem) {
    selectedGroupId.value = row.emgid;
  }

  // 用户选中事件
  function handleUserSelected(rows: GroupUserItem) {
    userSelected.value = rows;
  }

  function handleNoUserSelected(rows: GroupUserItem) {
    noUserSelected.value = rows;
  }

  // 移除选中用户从用户组
  async function handleRemoveUserFormGroup() {
    if (!userSelected.value) return;

    userListLoading.value = true;
    const detail = await removeUserFromGroup(
      userSelected.value.id,
      selectedGroupId.value
    );
    Message.success(detail);
    refreshUserList();
    recordOperateLog(OperationType.MallocUser);
  }

  // 添加选中用户到用户组
  async function handleAddUserToGroup() {
    if (!noUserSelected.value) return;

    noUserListLoading.value = true;
    const detail = await addUserToGroup(
      noUserSelected.value.id,
      selectedGroupId.value
    );

    Message.success(detail);
    refreshUserList();
    recordOperateLog(OperationType.MallocUser);
  }

  resetUserList = () => {
    userData.value = [];
    userList.value = [];
    noUserData.value = [];
    noUserList.value = [];
    userKeyword.value = "";
    noUserKeyword.value = "";
  };

  return {
    userList,
    noUserList,
    userKeyword,
    noUserKeyword,
    userListLoading,
    noUserListLoading,

    handleSelectGroup,
    handleUserSelected,
    handleNoUserSelected,
    handleAddUserToGroup,
    handleRemoveUserFormGroup
  };
}

export function useEditor() {
  const editor = reactive({
    show: false,
    target: {} as any
  });

  const that = getCurrentInstance();

  function openEditorWindow(row: UserGroupItem) {
    editor.target = clone(row);
    editor.show = true;
  }

  function closeEditorWindow() {
    editor.show = false;
  }

  /**
   * 检查修改表单
   */
  function handleCheckEditorForm() {
    (that.refs.editorForm as any).submit();
  }

  /**
   * 提交修改表单
   */
  async function handleSubmitEditorForm() {
    const detail = await updateUserGroup(editor.target);
    Message.success(detail);
    refreshGroupList();
    editor.show = false;
    recordOperateLog(OperationType.Update);
  }

  return {
    editor,
    openEditorWindow,
    closeEditorWindow,
    handleCheckEditorForm,
    handleSubmitEditorForm
  };
}

export function useAddit() {
  const addit = reactive({
    show: false,
    target: {} as any
  });

  const that = getCurrentInstance();

  function openAdditWindow() {
    addit.target = {
      emgname: "",
      emgtype: 1,
      detail: "",
      order: "",
      remark: ""
    };
    addit.show = true;
  }

  function closeAdditWindow() {
    addit.show = false;
  }

  /**
   * 新增表单检查
   */
  function handleCheckAdditForm() {
    (that.refs.additForm as any).submit();
  }

  /**
   * 新增表单提交
   */
  async function handleSubmitAdditForm() {
    const detail = await createUserGroup(addit.target);
    if (detail) {
      Message.success(`创建${detail.emgname}用户组成功`);
      refreshGroupList();
      addit.show = false;
      recordOperateLog(OperationType.Add);
    }
  }

  return {
    addit,
    openAdditWindow,
    closeAdditWindow,
    handleCheckAdditForm,
    handleSubmitAdditForm
  };
}

/**
 * 用户组类别
 */
export const groupTypeList: object[] = [
  { label: "设备操作类", value: 1 },
  { label: "媒体发送类", value: 2 },
  { label: "命令权限类", value: 3 },
  { label: "系统维护类", value: 4 },
  { label: "PAAS短信类", value: 5 },
  { label: "PAAS待处理用户类", value: 6 },
  { label: "轮值类", value: 7 }
];
